<template>
  <div class="hello" style="width: 100%">
    <h3 style="margin: 0 auto">{{ msg }}</h3>
    <div class="powerEcharts">
      <div ref="chartContainer" class="chart"></div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import {getAllPower,getOnePower,getAvg} from '@/api/echartApi'
export default {
  name: "HelloWorld",
  props: {
    msg: {
      type: String,
      default: "总进线",
    },
    type: {
      type: String,
      required: true,
    },
    current: {
      type: String,
      default: "202.1A",
    },
    value: {
      type: String,
      default: 202.1,
    },
    max: {
      type: String,
      default: 202.1,
    },
  },
  data() {
    return {
      chart: null,
      powerData: [],
      timer: null,
      flag: true,
      i: 0,
      datas: [
        { dateNum: "20250101", data: 100 },
        { dateNum: "20250102", data: 200 },
        { dateNum: "20250103", data: 300 },
        { dateNum: "20250104", data: 400 },
        { dateNum: "20250105", data: 500 },
        { dateNum: "20250106", data: 600 },
        { dateNum: "20250107", data: 700 },
        { dateNum: "20250108", data: 800 },
        { dateNum: "20250109", data: 900 },
        { dateNum: "20250110", data: 1000 },
        { dateNum: "20250111", data: 100 },
        { dateNum: "20250112", data: 200 },
        { dateNum: "20250113", data: 300 },
        { dateNum: "20250114", data: 400 },
        { dateNum: "20250115", data: 500 },
        { dateNum: "20250116", data: 600 },
        { dateNum: "20250117", data: 700 },
        { dateNum: "20250118", data: 800 },
        { dateNum: "20250119", data: 900 },
        { dateNum: "20250120", data: 1000 },
        { dateNum: "20250121", data: 100 },
        { dateNum: "20250122", data: 200 },
        { dateNum: "20250123", data: 300 },
        { dateNum: "20250124", data: 400 },
      ],
      interval: 40000,
      dates: 1,
      avg: 0,
      locate: ''
    };
  },
  watch: {

    type(newVal) {
        console.log(newVal);
        this.fetchPowerData(newVal);
      }
  },
  mounted() {
    // console.log(this.msg,this.type,this.value,this.max,this.current)
    this.flag = true;
    this.powerData = [];
    this.initChart();
    console.log(this.type)
    this.fetchPowerData(this.type);
    // Update chart every 5 minutes
    this.timer = setInterval(() => {
      this.flag = false;
      this.i++;
      this.dates++;
      // this.fetchPowerData(this.type);
      this.reFetchPowerData(this.type);
      // console.log(this.powerData)
      // this.getAvg(this.type).
    }, 300000);
    this.resizeHandler = () => {
      this.adjustChartSize(); // Call adjustChartSize on resize
    };
    window.addEventListener("resize", this.resizeHandler);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    isMobile() {
      // Basic check using userAgent or window width
      if (
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent
        )
      ) {
        return true;
      }
      // You can also check window width as a fallback or primary method
      // return window.innerWidth <= 768;
      return false; // Default to desktop
    },
    adjustChartSize() {
      if (!this.$refs.chartContainer) return;
      const container = this.$refs.chartContainer;
      if (this.isMobile()) {
        // Set width for mobile (e.g., 100% of viewport width minus padding)
        container.style.width = "calc(100vw - 40px)"; // Adjust 40px based on parent padding
        container.style.height = "300px"; // Adjust height for mobile if needed
        console.log("手机浏览器");
        this.interval = 1000;
        this.locate = 'middle'
      } else {
        // Set width for desktop (e.g., 100% of container)
        container.style.width = "100%";
        container.style.height = "500px"; // Original desktop height
        // console.log("电脑浏览器");
        this.interval = 400;
        this.locate = 'end'
      }
      // Resize the ECharts instance
      if (this.chart) {
        this.chart.resize();
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.adjustChartSize(); // Call adjustChartSize on init
      this.updateChart([]);
    },
   async fetchPowerData(name) {
     console.log('更新新数据')
      // axios
      //   .get(`http://192.168.5.16:3000/api/users/${name}`)
      //   .then((response) => {
      //     console.log(response.data);

      //     if (this.flag === true) {
      //       this.powerData = response.data;
      //       this.updateChart(this.powerData);
      //     }
      //     // else {
      //     //   this.powerData.shift();
      //     //   this.powerData.push(response.data[response.data.length - 1]);
      //     //   console.log(response.data[response.data.length - 1]);
      //     //   this.updateChart(this.powerData);
      //     // }
      //   })
      //   .catch((error) => {
      //     console.error("Error fetching power data:", error);
      //   });
      const res = await getAllPower(name)
      // console.log(res.data)
     const sum = res.data.reduce((total,item,index) => {return(total + item.DATA)}, 0)
      const avg = sum / res.data.length
      // console.log(avg,sum)
      this.powerData = res.data
     console.log(this.powerData)
      this.updateChart(this.powerData)
    },
    async reFetchPowerData(name) {
      const res = await axios.get(`http://192.168.5.16:3001/api/one/${name}`);
      console.log(res.data[0].DATA);
      this.powerData.push(res.data[0])
      this.updateChart(this.powerData)
    },
    updateChart(data) {
      // const concat = item => item.('CONCAT(RIGHT(date,6),CAST(hourF AS CHAR)'))
      console.log()
      const times = data.map((item) => ((item.date).slice(2)+-+item.HOURF+':'+item.MINUTEF)) || [];
      // const values = data.map((item) => (Math.trunc(item.DATA * 10) / 10).toFixed(1)) || [];
      const values = data.map(item => item.DATA) || []
      // const times = this.datas.map(item => item.dateNum) || []
      // const values = this.datas.map(item => item.data) || []
      const option = {
        title: {
          // text: this.msg,
          textAlign: "left",
          left: "100px",
        },
        tooltip: {
          trigger: "axis",
          formatter: "{b}<br />{a}: {c} A",
        },
        grid: {
          // right: '80%'
        },
        xAxis: {
          type: "category",
          data: times,
          boundaryGap: false,
          axisLabel: {
            interval: this.interval,
            rotate: 45,
            showMinLabel:true,
            showMaxLabel: true,
            fontSize: 14,
            fontWeight: 'bolder'
          },
        },
        yAxis: {
          max: this.max,
          type: "value",
          name: "电流 (A)",
          interval: 20,
          axisLabel: {
            fontSize: 16
          }
        },
        series: [
          {
            name: "电流值",
            type: "line",
            smooth: true,
            symbol: "none",
            data: values,
            markLine: {
              symbol: "none",
              data: [
                {
                  yAxis: this.value,
                  name: "阈值A",
                  lineStyle: { color: "#f07d74", type: "solid",width:3 },
                  label: {
                    show: true, // 显示标签
                    position: this.locate, // 标签位置：'start'、'middle'、'end'
                    formatter: `额定电流: ${this.current}`, // {c} 自动替换为 yAxis 值
                  },
                },
                // {
                //   yAxis: 110.45,
                //   name: '阈值B',
                //   lineStyle: { color: '#00b050', type: 'solid' },
                //   label:{
                //     show: true,   // 显示标签
                //     position: 'end', // 标签位置：'start'、'middle'、'end'
                //     formatter: '安全电流: {c}' // {c} 自动替换为 yAxis 值
                //   }
                // },
                {
                  type: 'average',
                  name: '平均电流',
                  lineStyle: {color:'#1a9f34', type: 'solid',width: 3},
                  label:{
                    show: true,
                    position: this.locate,
                    formatter: 'A项平均电流: {c}A'
                  }
                }
              ],
            },
          },
        ],
        dataZoom: [
          {
            type: "slider",
            show: true,
            start: 75,
            end: 100,
            bottom: 10,
            zoomLock: true,
            realtime: true,
            brushSelect: false,
            throttle: 800,
            handleStyle: {
              color: "#666", // 默认手柄颜色
              borderColor: "#999", // 默认边框颜色
              borderWidth: 1, // 默认边框宽度
              // 鼠标悬停时的样式
              emphasis: {
                color: "#ff4500", // 悬停颜色（橙色）
                borderColor: "#ff4500", // 悬停边框颜色
                borderWidth: 2, // 悬停边框加粗
              },
            },
            moveHandleStyle: {
              color: "rgba(100,100,100,0.3)", // 默认移动条颜色
              // 鼠标悬停时的样式
              emphasis: {
                color: "rgba(100,100,100,0.5)", // 悬停颜色加深
              },
            },
          },
          {
            type: "inside",
            start: 75,
            end: 100,
            zoomLock: true,
            filterMode: "filter",
          },
        ],
        grid: {
          bottom: 90,
          left: 90,
        },
      };

      this.chart.setOption(option);
      // let currentStart = 70
      // let currentEnd = 100
      // this.timer = setInterval(() => {
      //       // 每次向右移动 1%
      //       currentStart += 1;
      //       currentEnd += 1;

      //       // 如果超过 100%，重置到右侧（模拟连续数据）
      //       if (currentEnd > 100) {
      //           currentStart = 0;
      //           currentEnd = 70;
      //       }

      //       // 更新 dataZoom 配置
      //       this.chart.setOption({
      //           dataZoom: [{
      //               start: currentStart,
      //               end: currentEnd
      //           }]
      //       });
      //   }, 3000)
      // Handle window resize
      window.addEventListener("resize", () => {
        this.chart && this.chart.resize();
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
  height: 55vh;
  transform: translateY(-4%);
}
.powerEcharts {
  display: flex;
  justify-content: center;
  width: 100%;
}
.chart {
  width: 100% !important;
  /* height: 60vh !important; */
  height: 55vh !important;
  transform: translateY(-5%);
}
@media (max-width: 1200px) and (orientation: landscape) {
  .chart {
    width: 100% !important;
    height: 70vh !important;
  }
}
h3 {
  text-align: center;
}

</style>
